<template>
  <div class="container pos-rel">
    <div class="top-back" :style="'top: '+ personalTop + 'px;'"
      @click="pageBack">
      <label class="flex v-align-c">
        <icon class="iconfont icon-arrow-right"></icon>
      </label>
    </div>
    <img v-if="fileSpace" mode="aspectFill" @click="chooseImage"
      class="width-375 height-322 info-bg" :src="infoBg"/>    
    <div class="avatar-bar" :style="'top: '+ ( personalTop + 54 ) + 'px;'">
      <label class="pos-rel">
        <img v-if="fileSpace" :src="fileSpace + '/images/icon-v.png'" class="icon-v" alt="">
        <img class="a-img" :src="memberInfo.avatar" alt="">
      </label>
    </div>
    <div class="r-btn pad-15" :style="'top: '+ ( personalTop + 49 ) + 'px;'">
      <template v-if="friendId === getCustomerId">
        <label class="txt-label" @click="$pt.navigateTo({url:'/pages/personal/setting/main'})">
          编辑
        </label>
      </template>
      <label @click="qrCodeOpen">
        <img v-if="fileSpace" :src="fileSpace + '/images/icon-qrcode-2.png'" class="width-21 height-21" alt="">
        <div class="text-align-c"><img v-if="wxaCodeImg" :src="wxaCodeImg" class="width-1 height-1" alt=""></div>
      </label>
    </div>
    <div class="info-txt" :style="'top: '+ ( personalTop + 120 ) + 'px;'">
      <p class="font-19 pad-t-9 pad-b-9 text-shadow">{{ memberInfo.nickname }}</p>
      <p class="font-12 gray-col-t pad-b-5 text-shadow">
        关注 <span>{{ countFriends.followCount }}</span> 
        <label>|</label> 
        粉丝 <span>{{ countFriends.fansCount }}</span>
      </p>
      <div class="flex v-align-c font-10">
        <div v-if="memberInfo.gender || memberInfo.career" class="flex v-align-c info-label">
          <img v-if="fileSpace && memberInfo.gender === 1"
            :src="fileSpace + '/images/icon-man-2.png'" class="width-13 height-13 mar-r-4" alt="">
          <img v-if="fileSpace && memberInfo.gender === 2"
            :src="fileSpace + '/images/icon-woman-2.png'" class="width-13 height-13 mar-r-4" alt="">
          <label>{{ memberInfo.career }}</label>
        </div>
        <div v-if="cityName" class="info-label">{{ cityName }}</div>
      </div>
    </div>    
    <div class="info-main">
      <div class="height-33"></div>      
      <div>
        <h2>基本信息</h2>
        <p><span>昵称：</span>{{ memberInfo.nickname }}</p>
        <p v-if="memberInfo.gender">
          <span>性别：</span>
          <template v-if="memberInfo.gender === 1">男</template>
          <template v-if="memberInfo.gender === 2">女</template>
        </p>
        <p v-if="memberInfo.career"><span>职业：</span>{{ memberInfo.career }}</p>
        <p v-if="memberDetails.companyName"><span>公司：</span>{{ memberDetails.companyName }}</p>
        <p v-if="memberInfo.address"><span>地址：</span>{{ memberInfo.address }}</p>
        <p v-if="memberDetails.personalityName"><span>签名：</span>{{ memberDetails.personalityName }}</p>
      </div>
      <div class="mar-t-30 contact-info">
        <h2>联系方式</h2>
        <p v-if="memberInfo.wechatNo" class="flex v-align-c" @click="$pt.setClipboardData({data: memberInfo.wechatNo})">
          <label class="flex-item"><span>微信：</span>{{ memberInfo.wechatNo }}</label>
          <i>复制</i>
        </p>
        <p v-if="memberInfo.email" class="flex v-align-c" @click="$pt.setClipboardData({data: memberInfo.email})">
          <label class="flex-item"><span>邮箱：</span>{{ memberInfo.email }}</label>
          <i>复制</i>
        </p>
      </div>
      <div v-if="friendId !== getCustomerId" class="height-43"></div>
      <div v-if="friendId !== getCustomerId" class="change-shop font-w" @click="changeShop">访问TA的店铺</div>
      <div class="pad-t-15"></div>
    </div>
    <template v-if="wxaLayerBoolean">
      <div class="code-layer">
        <div class="code-con pos-rel">
          <div class="close-layer" @click="wxaLayerBoolean = false">
            <van-icon name="cross" size="30px" color="#dadada"/>
          </div>
          <div class="code-top">
            <h2>{{ qrCodeNikeName }}的智能云店</h2>
            <canvas canvas-id="wxaCodeCanvas" class="qr-code-canvas"></canvas>
            <p class="font-10">微信扫一扫上面的二维码图案，查看我店铺</p>
          </div>
          <button class="down-btn" @click="downPic('wxaCodeCanvas')">保存到手机</button>
          <div class="down-bg" @click="wxaLayerBoolean = false"></div>
        </div>      
      </div>
      <div class="code-layer-bg" @click="wxaLayerBoolean = false"></div>
    </template>
  </div>
</template>

<script>
  import { getMemberInfo, updateMember } from '@/api/home'
  import { getMemberWxaCode } from '@/api/common'
  import { shareCard } from '@/api/accessStat'
  import { saveFriends } from '@/api/friends'
  import { countMyFriends } from '@/api/personal'
  
  export default {
    data() {
      return {
        memberInfo: {},
        memberDetails: {},
        statusBarHeight: 0,
        personalTop: 0,
        qrCodeNikeName: '',
        wxaLayerBoolean: false,
        countFriends: {},
        friendId: '',
        infoBg: '',
        cityName: '',
        files: [],
        isUploadFinish: false,
        wxaCodeImg: ''
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      this.statusBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight'] + 44
      this.personalTop = this.statusBarHeight - 39
    },
    onShow() {
      this.friendId = this.getCurrentPage().query.friendId
      this.urlFrom = this.getCurrentPage().query.urlFrom
      this.initMemberInfo()
    },
    mounted() {
      this.getMemberWxaCode()
    },
    onShareAppMessage() {
      // 分享名片埋点
      this.$pt.setStorageSync('chooseLocation', true)
      shareCard(this.friendId)
      return {
        title: this.memberInfo.nickname + '的主页',
        path: 'pages/home/member-info/main?friendId=' + this.friendId,
        imageUrl: this.fileSpace + '/images/share-s-picture.png'
      }
    },
    methods: {
      getMemberWxaCode() {
        getMemberWxaCode({
          memberId: this.friendId
        }).then((response) => {
          if (response.isError) return
          this.wxaCodeImg = response.data
        }).catch(() => {
        })
      },
      pageBack() {
        if (this.urlFrom === 'inSide') {
          this.$pt.navigateBack({ delta: -1 })
        } else {
          this.$pt.reLaunch({ url: '/pages/home/main' })
        }
      },
      changeShop() {
        this.$utils.setMyId(this.friendId)
        this.$root.$mp.appOptions.query = {}
        this.$pt.reLaunch({ url: '/pages/home/main' })
      },
      chooseImage(e) {
        if (!this.checkOwner) return
        let that = this
        that.$pt.chooseImage({
          count: 1, // 默认9
          sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  original原图  compressed压缩图
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function(res) {
            that.$utils.showToast({
              title: '图片上传中',
              icon: 'loading',
              duration: 150000,
              mask: true
            })
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            // console.log(res)
            that.files = res.tempFilePaths
            // 获取上传图片的base64值
            // that.$pt.getFileSystemManager().readFile({
            //   filePath: res.tempFilePaths[0],
            //   encoding: 'base64',
            //   success: function(resData) {
            //     console.log('base64')
            //     console.log(resData.data)
            //   }
            // })
            that.doUpload()
          },
          fail: function(res) {
            this.$utils.showToast({ title: '图片选择失败，请重新选择！' })
          },
          complete: function(res) {
            console.log('complete')
          }
        })
      },
      doUpload() {
        const that = this
        this.files.forEach(file => {
          // 使用微信上传（只能单张上传）
          const uploadTask = that.$pt.uploadFile({
            url: process.env.BASE_API + '/common/uploadFiles',
            filePath: file,
            name: 'files',
            success(res) {
              const result = JSON.parse(res.data)
              if (result.statusCode >= 400) {
                that.$pt.hideToast()
                that.files = []
                return
              }
              if (result.code === 101) {
                that.$pt.hideToast()
                that.memberInfo.backImgUrl = result.data[0]
                updateMember(that.memberInfo).then((response) => {
                  if (response.isError) return
                  that.initMemberInfo()
                }).catch(() => {
                })
                // console.log(that.memberInfo.backImgUrl)
              } else {
                that.files = []
                that.$utils.showToast({ title: '图片上传发生错误:' + result.msg })
              }
            },
            complete(res) {
              if (res.statusCode >= 400 && res.statusCode !== 504) {
                that.$utils.showToast({ title: '当前网络不可用，请检查你的网络设置（' + res.statusCode + '）' })
                setTimeout(() => {
                  that.files = []
                  that.$pt.hideToast()
                }, 800)
              }
              if (res.statusCode === 504) {
                that.$utils.showToast({ title: '网络异常，请稍后再试（' + res.statusCode + '）' })
                setTimeout(() => {
                  that.files = []
                  that.$pt.hideToast()
                }, 800)
              }
            }
          })
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress)
          })
        })
      },
      // 收藏
      saveFriends() {
        let addFlag = 0
        if (this.memberInfo.friendsFlag === 1) {
          addFlag = 0
        } else {
          addFlag = 1
        }
        saveFriends({
          addFlag: addFlag,
          friendId: this.friendId,
          memberId: this.getCustomerId
        }).then((response) => {
          if (response.isError) return
          this.memberInfo.friendsFlag = addFlag
          this.countMyFriends()
          if (addFlag === 0) {
            this.$utils.showToast({ title: '已取消关注' })
          } else {
            this.$utils.showToast({ title: '关注成功' })
          }
        }).catch(() => {
        })
      },
      // 会员基本信息
      initMemberInfo() {
        getMemberInfo(this.friendId).then((response) => {
          if (response.isError) return
          this.memberInfo = response.data
          this.memberDetails = this.memberInfo.memberDetails
          if (this.memberInfo.nickname) {
            if (this.memberInfo.nickname.length > 5) {
              this.qrCodeNikeName = this.$utils.getStrByLens(this.memberInfo.nickname, 10) + '...'
            } else {
              this.qrCodeNikeName = this.$utils.getStrByLens(this.memberInfo.nickname, 10)
            }
          }
          if (!this.memberInfo.backImgUrl || this.memberInfo.backImgUrl === '') {
            this.infoBg = this.fileSpace + '/images/info-bg.jpg?imageView2/1/w/750/h/644'
          } else {
            this.infoBg = this.memberInfo.backImgUrl + '?imageView2/1/w/750/h/644'
          }
          // console.log(this.infoBg)
          if (this.memberInfo.address) {
            let address = this.memberInfo.address
            const reg = /.+?(省|市|自治区|自治州|县|区)/g
            if (address.match(reg)[1]) {
              this.cityName = address.match(reg)[1]
            } else {
              this.cityName = address.match(reg)[0]
            }
            if (address.match(reg)[0].indexOf('市') !== -1 || address.match(reg)[0].indexOf('行政区') !== -1) {
              this.cityName = address.match(reg)[0]
            }
            if (address.match(reg)[0].indexOf('自治区') !== -1) {
              this.cityName = address.match(reg)[1]
            }
            if (this.cityName.indexOf('市') !== -1) {
              this.cityName = this.cityName.replace(/市/, '')
            }
            if (this.cityName.indexOf('特别行政区') !== -1) {
              this.cityName = this.cityName.replace(/特别行政区/, '')
            }
          }
        }).catch(() => {
        })
        this.countMyFriends()
      },
      countMyFriends() {
        countMyFriends(this.friendId).then((response) => {
          if (response.isError) return
          this.countFriends = response.data
        }).catch(() => {
        })
      },
      qrCodeOpen() {
        if (!this.getShowBuyCard) return
        this.wxaLayerBoolean = true
        const that = this
        // canvas 使用的是px，如果要适应屏幕需要转化
        let rpx = that.$pt.getSystemInfoSync().windowWidth / 375
        that.$utils.showToast({
          title: '图片生成中',
          icon: 'loading',
          duration: 1000
        })
        const context = that.$pt.createCanvasContext('wxaCodeCanvas')
        // 清除画布，防止层叠
        context.clearRect(0, 0, 286 * rpx, 286 * rpx)
        that.$pt.downloadFile({
          url: that.wxaCodeImg,
          success: function(wxaCode) {
            context.drawImage(wxaCode.tempFilePath, 0 * rpx, 0 * rpx, 286 * rpx, 286 * rpx)
            context.draw(true)
          }
        })
      },
      downPic(canvasId) {
        const that = this
        that.$pt.canvasToTempFilePath({
          canvasId: canvasId,
          success: (res) => {
            const filePath = res.tempFilePath
            if (filePath) {
              that.$pt.saveImageToPhotosAlbum({
                filePath: filePath,
                success: (res) => {
                  that.$utils.showToast({ title: '保存成功，请到手机相册查看' })
                },
                fail: function(err) {
                  if (err.errMsg.indexOf('cancel') !== -1) return
                  that.$pt.showModal({
                    content: '保存图片需要访问你的相册',
                    success(res) {
                      if (res.confirm) {
                        that.$pt.openSetting()
                      } else if (res.cancel) {
                        console.log(err)
                      }
                    }
                  })
                }
              })
            }
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .container{
    background: #fff;
    // min-height: calc(100vh - 70px);
    min-height: 100vh;
    overflow: hidden;
  }
  .change-shop{
    background: #3f3f3f;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    color: #fff;
    font-size: 15px;
    text-align: center;
    padding: 10px 0;
    z-index: 10;
  }
  .text-shadow{
    text-shadow:0 1px 2px rgba(0, 0, 0, 0.6)
  }
  .code-layer{
    position: fixed;
    left: 50%;
    top: 50%;
    z-index: 60;
    width: 346px;
    margin: -245px 0 0 -173px;
    text-align: center;
    .close-layer{
      position: absolute;
      right: 7px;
      top: 7px;
      width: 35px;
      height: 35px;
      z-index: 22;
      /deep/ .van-icon{
        display: block;
      }
    }
    .code-top{
      background: #fff;
      border-radius: 10px;      
      h2{
        margin: 0;
        padding: 25px 0 35px 0;
        font-size: 25px;
        line-height: normal;
        display: block;
      }
      .qr-code-canvas{
        width: 286px;
        height: 286px;
        margin: 0 auto;
      }
      img{
        display: inline-block;
      }
      p{
        display: block;
        padding: 40px 0 30px 0;
        color: #818181;
      }
    }
    .down-btn{
      display: inline-block;
      background: #ffe200;
      border-radius: 200px;
      font-size: 19px;
      line-height: normal;
      color: #595959;
      margin: 17px auto 0 auto;
      padding: 10px 52px;
      position: relative;
      z-index: 30;
      &:after{
        content: '';
        display: none;
      }
    }
    .down-bg{
      position: relative;
      z-index: 29;
      height: 80px;
      margin-top: -68px;
      // background: #ddd;
    }
  }
  .code-layer-bg{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.2);
    z-index: 59;
  }
  .info-bg{
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    width: 100%;
  }
  // 返回按钮样式
  .top-back{
    position: fixed;
    left: 0px;
    top: 28px;
    z-index: 101;
    padding: 8px 10px 8px 7px;
    .iconfont{      
      font-size: 20px;
      font-weight: bold;
      color: #fff;
      transform:rotate(180deg);
    }
  }
  .top-bar{
    position: relative;
    z-index: 5;
    margin: 73px 15px 0 15px;
    color: #fff;    
  }
  .avatar-bar{
    display: inline-block;
    position: absolute;
    left: 15px;
    top: 0;
    z-index: 50;
    color: #fff;
    label{
      display: inline-block;
      width: 65px;
      height: 65px;
      background: #fff;
      border-radius: 50%;
      z-index: 30;
    }
    .icon-v{
      width: 24px;
      height: 24px;
      position: absolute;
      right: 0px;
      bottom: 0px;
    }
    .a-img{
      width: 65px;
      height: 65px;
      border-radius: 100px;
      box-shadow: 0 4px 9px rgba(0, 0, 0, 0.2);
    }
  }
  .r-btn{
    text-align: center;
    position: absolute;
    right: 0px;
    top: 0;
    z-index: 50;
    color: #fff;
    label{
      display: inline-block;
      vertical-align: top;
      font-size: 15px;
      background: #4b4b4d;
      border-radius: 5px;
      padding: 6px 6px 0 6px;
      margin-left: 4px;
      box-sizing: border-box;
      height: 34px;
      line-height: 34px;
      &.txt-label{
        padding: 0 15px 0px 15px;        
      }
    }
  }
  .info-txt{
    display: inline-block;
    position: absolute;
    left: 15px;
    top: 0;
    z-index: 50;
    color: #fff;
    p{
      span{
        padding: 0 5px;
      }
      label{
        padding-left: 2px;
        padding-right: 5px;
      }
      &.gray-col-t{
        color: #dadada;
      }
    }
    .info-label{
      background: #4b4b4d;
      border-radius: 50px;
      padding: 3px 9px;
      margin-right: 8px;
      &:last-child{
        margin-right: 0;
      }
    }
  }
  .info-main{
    background: #fff;
    padding: 0 15px;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    position: relative;
    z-index: 5;
    margin-top: 280px;
    h2{
      margin: 0 0 9px 0;
      font-weight: bold;
      font-size: 13px;
      color: #292929;
    }
    .contact-info{
      p{
        padding: 0 0 8px 0;
      }
    }
    p{
      font-size: 12px;
      color: #595959;
      padding: 0 0 4px 0;
      span{
        color: #818181;
      }
      i{
        border-radius: 3px;
        background: #ffc808;
        color: #fff;
        padding: 1px 6px;
      }
    }
  }
</style>
